package com.yc.c118s3qnzf.controller;

import com.yc.c118s3qnzf.entity.Users;
import com.yc.c118s3qnzf.service.BizException;
import com.yc.c118s3qnzf.service.IUsersService;
import com.yc.c118s3qnzf.vo.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2022-11-28
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Resource
    IUsersService usersService;

    @GetMapping("login")
        public Result login(@Valid Users users, Errors errors, HttpSession session) {
        if (errors.hasFieldErrors("username")
                || errors.hasFieldErrors("password")) {
            return new Result(0, "输入错误！", errors.getAllErrors());
        }
        try {
            Users login = usersService.login(users);

        } catch (BizException e) {
            errors.reject("login.error", e.getMessage());
            return new Result(0, "登录错误！", errors.getAllErrors());
        }
        return new Result(1, "登录成功！", null);
    }

    @RequestMapping("logout")
    Result logout(HttpSession session) {
        session.invalidate();
        return new Result(1, "退出成功", null);
    }

    @RequestMapping("getLoginedUser")
    Result getLoginedUser(@SessionAttribute(required = false) Users loginedUser) {
        //session.getAttribute("loginedUser");
        if (loginedUser == null) {
            return new Result(0, "未登录", null);

        } else {
            loginedUser.setPassword(null);
            return new Result(1, "已登录", loginedUser);
        }
    }
}

